<?php

namespace App\Http\Middleware;

use Auth;
use App\Service\Traits\ApiResponse;
use Symfony\Component\HttpFoundation\Response as FoundationResponse;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\JWTException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

class JwtAuthenticate extends BaseMiddleware
{
    use ApiResponse;
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, \Closure $next)
    {

        if (!$token = $this->auth->setRequest($request)->getToken()) {
            return $this->failed('token is empty',FoundationResponse::HTTP_UNAUTHORIZED);
        }

        try {
            if ($this->auth->parseToken()->authenticate()) {
                return $next($request);
            }
            //JWTAuth::toUser($token);
        }catch (\Exception $e) {
            if($e instanceof TokenExpiredException){
                try {
                    // 刷新用户的 token
                    $token = $this->auth->refresh();
                   // 使用一次性登录以保证此次请求的成功
                    Auth::guard('api')->onceUsingId($this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub']);
                } catch (JWTException $exception) {
                   // 如果捕获到此异常，即代表 refresh 也过期了，用户无法刷新令牌，需要重新登录。
                   return $this->failed('登录已过期,请重新登录');
                  //throw new UnauthorizedHttpException('jwt-auth', $exception->getMessage());
                }
            }
            //return $this->failed('用户登录失效',FoundationResponse::HTTP_UNAUTHORIZED);
        }
        return $this->setAuthenticationHeader($next($request), $token);

    }
}
